package com.jay.compass;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jay.compass.adapter.MessageAdapter;
import com.jay.compass.adapter.MessageAdapter.ItemLongClickListener;
import com.jay.compass.app.StarApplication;
import com.jay.compass.base.MessageItem;
import com.jay.compass.base.RecentItem;
import com.jay.compass.ble.BluetoothLeService;
import com.jay.compass.database.MessageDB;
import com.jay.compass.database.RecentDB;
import com.jay.compass.utils.BTimer;
import com.jay.compass.utils.SharePreferenceUtil;
import com.pzf.liaotian.xlistview.MsgListView;
import com.pzf.liaotian.xlistview.MsgListView.IXListViewListener;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.text.ClipboardManager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class ChatActivity extends Activity implements OnTouchListener,
		ItemLongClickListener, IXListViewListener {
	private Toast mToast;
	private MessageDB mMsgDB;
	private RecentDB mRecentDB;
	private StarApplication mApplication;
	private MsgListView mMsgListView;
	private static MessageAdapter adapter;
	public static int MSGPAGERNUM;
	private SharePreferenceUtil mSpUtil;
	private String mUserId;
	private String mUserName = "";
	private TextView titleTextView;
	private Button sendButton;
	private EditText msgEditText;

	private int mConnectType = LoginActivity.CONNECT_TYPE_NONE;
	private int mConnectStatus = 0;
	private String mSendMsg;
	private ProgressDialog sendingDialog;
	private Handler mSendHandler = new Handler();

	public BluetoothLeService mBluetoothLeService;
	private PopupWindow popupWindow;
	private View popView;
	private View mTempParent;
	private TextView popCopy;
	private TextView popDelete;
	private boolean isInBack = false;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			int left = msg.what;
			System.out.println("left time = " + left + "s");
			if (left > 0) {
				sendButton.setEnabled(false);
				sendButton.setText("(" + left + "s)");
			} else if (left == 0) {
				sendButton.setEnabled(true);
				sendButton.setText("发送");
			}

		};
	};

	private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
				System.out.println("gatt connected");
			} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED
					.equals(action)) {
				showTip("断开连接");
				MainActivity.mConnectStatus = 0;
				finish();
			} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED
					.equals(action)) {
			} else if (BluetoothLeService.ACTION_DEVICE_FIND.equals(action)) {
			} else if (BluetoothLeService.ACTION_GATT_TOAST.equals(action)) {
				// if (isInBack)
				// return;
				showTip(intent
						.getStringExtra(BluetoothLeService.BROADCAST_TO_TOAST));
			} else if (BluetoothLeService.ACTION_GATT_NEW_MESSAGE
					.equals(action)) {
				String id = intent
						.getStringExtra(BluetoothLeService.NEW_MESSAGE_ID);
				String msg = intent
						.getStringExtra(BluetoothLeService.NEW_MESSAGE_MESSAGE);
				String name = "";
				long time = System.currentTimeMillis();

				int headRes = R.drawable.head_bg;
				name = getContactNameFromPhoneBook(ChatActivity.this, id);
				if (name.length() < 1) {
					String tempId = id.substring(0, 3) + " "
							+ id.substring(3, 7) + " " + id.substring(7, 11);
					name = getContactNameFromPhoneBook(ChatActivity.this,
							tempId);
				}
				if (name.length() < 1) {
					name = id;
					headRes = R.drawable.head_phone;
				}

				if (isInBack) {
					StarApplication.getInstance().showNotification(name, msg);
				}

				int new_num = StarApplication.getInstance().getRecentDB()
						.getRecentNewNum(id);

				if (!mUserId.equals(id)) {
					new_num++;
				}

				StarApplication.getInstance().getMediaPlayer().start();
				RecentItem item = new RecentItem(RecentItem.MESSAGE_TYPE_TEXT,
						id, headRes, name, msg, new_num, time, 0);
				StarApplication.getInstance().getRecentDB().saveRecent(item);

				MessageItem msgItem = new MessageItem(
						MessageItem.MESSAGE_TYPE_TEXT, id, time, msg, headRes,
						true, 1, 0, id);

				StarApplication.getInstance().getMessageDB()
						.saveMsg(id, msgItem);

				System.out.println("id = " + id);
				System.out.println("userId = " + mUserId);
				if (mUserId.equals(id)) {
					adapter.upDateMsg(msgItem);
				}
			} else if (BluetoothLeService.ACTION_GATT_SEND_SUCCESS
					.equals(action)) {
				if (sendingDialog.isShowing()) {
					sendingDialog.dismiss();
				}

				long time = System.currentTimeMillis();
				int headRes = StarApplication.getHeads()[Integer
						.valueOf(mUserId.substring(mUserId.length() - 1)) % 10];

				if (isMobileNum(mUserId)) {
					headRes = R.drawable.head_bg;
					if (mUserName.getBytes().length == mUserName.length()) {
						headRes = R.drawable.head_phone;
					}
				} else {
					mUserName = mUserId;
				}

				int new_num = StarApplication.getInstance().getRecentDB()
						.getRecentNewNum(mUserId);

				RecentItem item = new RecentItem(RecentItem.MESSAGE_TYPE_TEXT,
						mUserId, headRes, mUserName, mSendMsg, new_num, time, 0);
				StarApplication.getInstance().getRecentDB().saveRecent(item);
				MessageItem msgItem = new MessageItem(
						MessageItem.MESSAGE_TYPE_TEXT, mUserName, time,
						mSendMsg, headRes, false, 0, 0, mUserId);
				adapter.upDateMsg(msgItem);
				StarApplication.getInstance().getMessageDB()
						.saveMsg(mUserId, msgItem);

				scrollToBottomListItem();
				msgEditText.setText("");

			} else if (BluetoothLeService.ACTION_GATT_SEND_FAILED
					.equals(action)) {
				if (sendingDialog.isShowing()) {
					sendingDialog.dismiss();
				}
				showTip("发送失败");
			}
		}
	};

	public String getContactNameFromPhoneBook(Context context, String phoneNum) {
		String contactName = "";
		ContentResolver cr = context.getContentResolver();
		Cursor pCur = cr.query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
				ContactsContract.CommonDataKinds.Phone.NUMBER + " = ?",
				new String[] { phoneNum }, null);
		if (pCur.moveToFirst()) {
			contactName = pCur
					.getString(pCur
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
			pCur.close();
		}
		return contactName;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// getWindow().setFlags(
		// WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
		// WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_chat);
		mUserId = getIntent().getStringExtra(FragmentChat.USER_ID);
		mUserName = getIntent().getStringExtra(FragmentChat.USER_NAME);

		System.out.println("user id = " + mUserId);
		System.out.println("user name = " + mUserName);

		mApplication = StarApplication.getInstance();
		mMsgDB = mApplication.getMessageDB();
		mRecentDB = mApplication.getRecentDB();
		mSpUtil = mApplication.getSpUtil();

		adapter = new MessageAdapter(this, initMsgData(), this);
		mMsgListView = (MsgListView) findViewById(R.id.msg_listView);
		mMsgListView.setOnTouchListener(this);
		mMsgListView.setPullLoadEnable(false);
		mMsgListView.setXListViewListener(this);
		mMsgListView.setAdapter(adapter);
		mMsgListView.setSelection(adapter.getCount() - 1);

		initView();
		mConnectStatus = MainActivity.mConnectStatus;
		mConnectType = MainActivity.mConnectType;
		mBluetoothLeService = mApplication.getBleService();
		if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
			registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
		}
	}

	private static IntentFilter makeGattUpdateIntentFilter() {
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
		intentFilter
				.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
		intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
		intentFilter.addAction(BluetoothLeService.ACTION_DEVICE_FIND);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_TOAST);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_NEW_MESSAGE);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_SEND_SUCCESS);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_SEND_FAILED);

		return intentFilter;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		isInBack = false;
		BTimer.getInstance().setHandler(mHandler);
		System.out.println("+onResume+");
		if (BTimer.getInstance().isRunning()) {
			int time = BTimer.getInstance().gettimeleft();
			sendButton.setEnabled(false);
			sendButton.setText("(" + time + "s)");
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		isInBack = true;
		BTimer.getInstance().setHandler(null);
		System.out.println("+onPause+");
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		System.out.println("+onDestroy+");
		if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
			unregisterReceiver(mGattUpdateReceiver);
		}
	}

	private void initView() {
		titleTextView = (TextView) findViewById(R.id.chat_title_textview);
		if (!isMobileNum(mUserId)) {
			mUserName = "";
		}
		titleTextView.setText(mUserName/* + mUserId */);
		sendButton = (Button) findViewById(R.id.send_btn);
		msgEditText = (EditText) findViewById(R.id.msg_et);

		sendButton.setOnClickListener(new View.OnClickListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String message = msgEditText.getEditableText().toString();
				String id = mUserId;
				mSendMsg = message;

				if (message.length() < 1) {
					showTip("无法发送空的内容");
					return;
				}

				if (isMobileNum(mUserId)) {

					byte[] head = new byte[13];
					head[0] = 0x00;
					head[1] = (byte) 0xbe;

					String number = mUserId;
					// get date
					Date date = new Date();
					int year = date.getYear() % 100;
					int month = date.getMonth() % 100 + 1;
					int day = date.getDate() % 100;

					int hour = date.getHours() % 100;
					int min = date.getMinutes() % 100;
					int sec = date.getSeconds() % 100;
					head[2] = (byte) (year / 10 * 16 + year % 10);
					head[3] = (byte) (month / 10 * 16 + month % 10);
					head[4] = (byte) (day / 10 * 16 + day % 10);
					head[5] = (byte) (hour / 10 * 16 + hour % 10);
					head[6] = (byte) (min / 10 * 16 + min % 10);
					head[7] = (byte) (sec / 10 * 16 + sec % 10);

					double num;
					if (number.length() == 11) {
						num = Double.valueOf(number);
					} else {
						showTip("手机号码错误");
						return;
					}

					head[8] = (byte) ((num / 256 / 256 / 256 / 256) % 256);
					head[9] = (byte) ((num / 256 / 256 / 256) % 256);
					head[10] = (byte) ((num / 256 / 256) % 256);
					head[11] = (byte) ((num / 256) % 256);
					head[12] = (byte) (num % 256);

					int content_len = message.length();
					if (content_len < 1) {
						showTip("输入信息为空");
						return;
					}
					byte[] content = null;
					try {
						content = message.getBytes(BluetoothLeService.encoding);
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					byte[] total = new byte[13 + content.length];
					int index = 0;
					for (int i = 0; i < 13; i++) {
						total[index++] = head[i];
					}
					for (int i = 0; i < content.length; i++) {
						total[index++] = content[i];
					}

					for (int i = 0; i < total.length; i++) {
						System.out.print(String.format("%02x ", total[i]));
					}
					System.out.println();
					id = MainActivity.PHONE_BEIDOU_ID;
					System.out.println("is phone number");
					if (mConnectStatus == 0) {
						showTip("请先连接设备");
						return;
					}

					System.out.println("id = " + id);
					System.out.println("message = " + message);

					if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
						sendingDialog = ProgressDialog.show(ChatActivity.this,
								"发送中", "请稍后...");
						mBluetoothLeService.sendCommand(
								MainActivity.SEND_TYPE_SMSG, id, null, total);
						mSendHandler.postDelayed(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								if (sendingDialog.isShowing()) {
									sendingDialog.dismiss();
									showTip("发送超时");
								}
							}
						}, 10000);
						if (!sendingDialog.isShowing())
							sendingDialog.show();
					}
				} else {

					if (mConnectStatus == 0) {
						showTip("请先连接设备");
						return;
					}

					System.out.println("id = " + id);
					System.out.println("message = " + message);

					if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
						sendingDialog = ProgressDialog.show(ChatActivity.this,
								"发送中", "请稍后...");
						mBluetoothLeService.sendCommand(
								MainActivity.SEND_TYPE_TXSQ, id, message, null);
						mSendHandler.postDelayed(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								if (sendingDialog.isShowing()) {
									sendingDialog.dismiss();
									showTip("发送超时");
								}
							}
						}, 10000);
						if (!sendingDialog.isShowing())
							sendingDialog.show();
					}
				}
			}
		});
	}

	private List<MessageItem> initMsgData() {
		List<MessageItem> list = mMsgDB.getMsg(mUserId, MSGPAGERNUM);
		System.out.println("list count = " + list.size());
		List<MessageItem> msgList = new ArrayList<MessageItem>();// 消息对象数组
		if (list.size() > 0) {
			for (MessageItem entity : list) {
				if (entity.getName().equals("")) {
					entity.setName("默认");
				}
				if (entity.getHeadImg() < 0) {
					entity.setHeadImg(0);
				}
				msgList.add(entity);
			}
		}
		return msgList;

	}

	/**
	 * @Description 滑动到列表底部
	 */
	private void scrollToBottomListItem() {
		// todo eric, why use the last one index + 2 can real scroll to the
		// bottom?
		if (mMsgListView != null) {
			mMsgListView.setSelection(adapter.getCount() + 1);
		}
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		MSGPAGERNUM++;
		List<MessageItem> msgList = initMsgData();
		int position = adapter.getCount();
		adapter.setmMsgList(msgList);
		mMsgListView.stopRefresh();
		mMsgListView.setSelection(adapter.getCount() - position - 1);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean isMobileNum(String mobiles) {
		if (mobiles.length() < 5)
			return false;
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	@Override
	public void onLongClick(View parent) {
		// TODO Auto-generated method stub
		System.out.println("chat onLongClick");
		showWindow(parent);
	}

	private void showWindow(View parent) {

		mTempParent = parent;
		if (popupWindow == null) {
			LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			popView = layoutInflater.inflate(R.layout.popup_layout, null);

			popCopy = (TextView) popView.findViewById(R.id.item_copy);
			popCopy.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					ClipboardManager c = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
					int pos = Integer.parseInt(mTempParent.getTag().toString());

					c.setText(((MessageItem) adapter.getItem(pos)).getMessage());
					popupWindow.dismiss();
					showTip("已复制到剪切板");
				}
			});
			popDelete = (TextView) popView.findViewById(R.id.item_delete);
			popDelete.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					int pos = Integer.parseInt(mTempParent.getTag().toString());
					System.out.println("pos = " + pos);
					MessageItem msgItem = (MessageItem) adapter.getItem(pos);
					// process recent db
					LinkedList<RecentItem> itemList = StarApplication
							.getInstance().getRecentDB().getRecentList();
					System.out.println("size = " + itemList.size());
					for (int i = 0; i < itemList.size(); i++) {
						RecentItem item = itemList.get(i);

						if (item.getMessage().equals(msgItem.getMessage())
								&& (item.getTime() == msgItem.getDate())) {
							StarApplication.getInstance().getRecentDB()
									.delRecent(item.getUserId());
							if (adapter.getCount() > 1) {
								MessageItem msg = (MessageItem) adapter
										.getItem(adapter.getCount() - 2);
								RecentItem it = new RecentItem(
										RecentItem.MESSAGE_TYPE_TEXT, msg
												.getId(), msg.getHeadImg(), msg
												.getName(), msg.getMessage(),
										StarApplication.getInstance()
												.getRecentDB().getRecentList()
												.size(), msg.getDate(), 0);
								StarApplication.getInstance().getRecentDB()
										.saveRecent(it);
							}
						}
					}

					StarApplication.getInstance().getMessageDB()
							.delMsg(msgItem.getId(), msgItem);
					adapter.removeMsg(pos);
					popupWindow.dismiss();
				}
			});

			popupWindow = new PopupWindow(popView, LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);
		}

		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);

		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		// int xPos = windowManager.getDefaultDisplay().getWidth() / 2
		// + popupWindow.getWidth() / 2;
		popupWindow.showAsDropDown(parent, 0, 0);
	}

	private void showTip(final String str) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mToast.setText(str);
				mToast.show();
			}
		});
	}
}
